package com.zhang.gmall.realtime.utils;

import com.zhang.gmall.realtime.beans.TransientSink;
import com.zhang.gmall.realtime.common.GmallConfig;
import org.apache.flink.connector.jdbc.JdbcConnectionOptions;
import org.apache.flink.connector.jdbc.JdbcExecutionOptions;
import org.apache.flink.connector.jdbc.JdbcSink;
import org.apache.flink.connector.jdbc.JdbcStatementBuilder;
import org.apache.flink.streaming.api.functions.sink.SinkFunction;

import java.lang.reflect.Field;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * @title: ClickHouse工具类
 * @author: zhang
 * @date: 2022/3/14 21:57
 */
public class ClickHouseUtil {
    public static <T> SinkFunction<T> getSinkFunction(String sql) {
        SinkFunction<T> sinkFunction = JdbcSink.<T>sink(
                sql,
                new JdbcStatementBuilder<T>() {
                    @Override
                    public void accept(PreparedStatement statement, T t) throws SQLException {
                        //获取属性对象
                        Field[] fields = t.getClass().getDeclaredFields();
                        int offset = 0;
                        for (int i = 0; i < fields.length; i++) {
                            Field field = fields[i];
                            //设置私有属性访问权限
                            field.setAccessible(true);
                            //获取属性值
                            try {
                                Object fieldValue = field.get(t);
                                if (field.getAnnotation(TransientSink.class) != null) {
                                    offset++;
                                    continue;
                                }
                                statement.setObject(i + 1 - offset, fieldValue);
                            } catch (IllegalAccessException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                },
                new JdbcExecutionOptions.Builder()
                        .withBatchSize(5)
                        .withBatchIntervalMs(5000L)
                        .withMaxRetries(3)
                        .build(),
                new JdbcConnectionOptions.JdbcConnectionOptionsBuilder()
                        .withDriverName(GmallConfig.CLICKHOUSE_DRIVER)
                        .withUrl(GmallConfig.CLICKHOUSE_URL)
                        .build()
        );

        return sinkFunction;
    }
}
